import 'package:elevator/model/signal_info.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';

import '../../../../../../../../model/build_info.dart';
import '../../../../../../../../model/lift_info.dart';
import 'package:mysql1/mysql1.dart' as mysql;

import '../../../../../../../../utils/eventbus.dart';

class FirstLogic extends GetxController {

  BuildInfo buildInfo;
  LiftInfo liftInfo;
  var signalInfoList = <SignalInfo>[].obs;

  FirstLogic(this.buildInfo,this.liftInfo);

  @override
  void onInit() {
    querySignalData(buildInfo.buildId);
    super.onInit();
  }

  @override
  void onReady() {

    super.onReady();
  }

  void register(){
    bus.on('${bus.liftInfo_Key}${buildInfo.buildId}_${liftInfo.order}', busCallback);
  }

  void unregister(){
    bus.off('${bus.liftInfo_Key}${buildInfo.buildId}_${liftInfo.order}', busCallback);
  }


  busCallback(arg){
    liftInfo = arg;
    updateLiftInfo();
  }

  @override
  void onClose() {
    debugPrint("FirstLogic:onClose:liftInfo_${buildInfo.buildId}_${liftInfo.order}");

    super.onClose();
  }

  querySignalData(String buildId) async {
    debugPrint("start querySignalData $buildId");
    var settings = mysql.ConnectionSettings(
        host: '36.141.45.30',
        port: 43306,
        user: 'root',
        password: 'adminemqx123',
        db: 'liftdb_$buildId',
        useCompression: false,
        timeout:const Duration(seconds: 60),
        maxPacketSize:16 * 1024 * 1024 *1024,
        characterSet: mysql.CharacterSet.UTF8MB4);
    var conn = await mysql.MySqlConnection.connect(settings);

    var signalResluts = await conn
        .query("select * from tbappsignalsheet");

    List<SignalInfo> signalInfos = [];
    for (var row in signalResluts) {
      if(row.length>=10){
        SignalInfo signalInfo = SignalInfo.builder(row);
        liftInfo.getTpcSignalBgColor(signalInfo);
        signalInfos.add(signalInfo);
      }
    }
    await conn.close();
    signalInfoList.value = signalInfos;
    debugPrint("楼盘 $buildId signalInfo加载完毕：${signalInfoList.length}条");
    signalInfoList.refresh();
  }

  void updateLiftInfo() {
    for (SignalInfo signalInfo in signalInfoList) {
      liftInfo.getTpcSignalBgColor(signalInfo);
    }
    signalInfoList.refresh();
  }
}
